package com.fxsh168.server.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Toast;



import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Date;


public abstract class BaseFragment extends Fragment {
    private static final int PHOTO_REQUEST = 1;
    private static final int CAMERA_REQUEST = 2;

    // 初始化网络链接
//
//    public HttpApi httpApi() {
//        Retrofit retrofit = new Retrofit.Builder()
//                .baseUrl("http://www.jidus.tk/")
//                .addConverterFactory(GsonConverterFactory.create())
//                .build();
//        HttpApi httpApi = retrofit.create(HttpApi.class);
//        return httpApi;
//    }

    //..........跳转页面的方法。。。。。。。。。。//
    public void jumpActivity(Class<?> tClass, Bundle bundle) {
        Intent intent = new Intent(getContext(), tClass);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    public void jumpActivity(Class<?> tClass) {
        this.jumpActivity(tClass, null);
    }

    public void jumpActivity(String action, Bundle bundle) {
        Intent intent = new Intent(action);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    //。..........................toast............................、//
    private Toast toast;

    //显示指定的字符串
    public void showToast(String msg) {
        if (toast != null) {
            toast.cancel();
        }
        toast = Toast.makeText(getContext(), msg, Toast.LENGTH_LONG);
        toast.show();
    }

    //显示资源id对应的字符串
    public void showToast(int resId) {
        if (toast != null) {
            toast.cancel();
        }
        toast = Toast.makeText(getContext(), resId, Toast.LENGTH_LONG);
        toast.show();
    }


    //    判断字符串是否为空
    public static boolean isEmpty(@Nullable CharSequence str) {
        if (str == null || str.length() == 0) {
            return true;
        } else {
            return false;
        }
    }

    //  根据手机的分辨率从 dip 的单位 转成为 px(像素)
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    //      根据手机的分辨率从 px(像素) 的单位 转成为 dp
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    //  获取手机的分辨率px，返回一个数组，为宽度和长度。
    public static int[] getDevicePx(Activity activity) {
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int width = metrics.widthPixels;
        int heigth = metrics.heightPixels;
        return new int[]{width, heigth};
    }
    public void playVoce(int who, Context context) {
        Uri u = null;
        //语音,下
        if (who == 1) {
            u = Uri.parse(Environment.getExternalStorageDirectory() + "/sound/down.mp3");//
        } else if (who == 2) {
            u = Uri.parse(Environment.getExternalStorageDirectory() + "/sound/up.mp3");//
        } else if (who == 3) {
            u = Uri.parse(Environment.getExternalStorageDirectory() + "/sound/new.mp3");//
        }
        MediaPlayer mPlayer;
        mPlayer = MediaPlayer.create(context, u);
        Log.e("tag", "获取地址" + u);
        //判断播放状态
        if (mPlayer.isPlaying()) {
            mPlayer.stop();
            mPlayer.release();
            mPlayer.start();
        } else {
            mPlayer.start();
        }
    }

    //          图片裁剪--------------------------------------------------
    public void photoClip(Uri uri) {
        // 调用系统中自带的图片剪裁
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 16);
    }

    /**
     * 转换图片成圆形---------------------------------------------------------------
     *
     * @param bitmap 传入Bitmap对象
     * @return
     */

    public Bitmap toRoundBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
        if (width <= height) {
            roundPx = width / 2;
            top = 0;
            bottom = width;
            left = 0;
            right = width;
            height = width;
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;
            float clip = (width - height) / 2;
            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }
        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
        final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
        final RectF rectF = new RectF(dst);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);
        return output;
    }

    //    获取年月日的方法
    public String getYears(String h) {
        Calendar cld = Calendar.getInstance();
        Date date = new Date();
        cld.setTime(date);
        int year = cld.get(Calendar.YEAR);
        int intMon = cld.get(Calendar.MONTH) + 1;
        int intDay = cld.get(Calendar.DAY_OF_MONTH);
        int hours = cld.get(Calendar.HOUR_OF_DAY);
        int minutes = cld.get(Calendar.MINUTE);
        if (h.equals("y")) {
            return year + "";
        } else if (h.equals("m")) {
            return intMon + "";
        } else if (h.equals("d")) {
            return intDay + "";
        } else if (h.equals("h")) {
            return hours + "";
        } else if (h.equals("m")) {
            return minutes + "";
        }else {
            return "";
        }
    }

    //           MD5  32位加密
    public String getMD5Str(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            System.out.println("NoSuchAlgorithmException caught!");
            System.exit(-1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        byte[] byteArray = messageDigest.digest();

        StringBuffer md5StrBuff = new StringBuffer();

        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        return md5StrBuff.toString();
    }

    private static final String PHOTO_FILE_NAME = "PHOTOIMAGE_ANSWER.jpg";

    //打开相机
    public void getPicFromCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 下面这句指定调用相机拍照后的照片存储的路径
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
        startActivityForResult(intent, CAMERA_REQUEST);
    }

    //打开相册
    public void getPicFromPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, PHOTO_REQUEST);
    }

    //       点击图标结束当前页面，返回上一个界面
    public View.OnClickListener returnActivity = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getActivity().finish();
        }
    };


    //   数据储存
    public void creteShare(String name, String pass, String token, Context context) {
        SharedPreferences mSharedPreferences = context.getSharedPreferences("loginUser", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString("tel", name);
        editor.putString("token", token);
        editor.commit();
    }

    //  数据清空
    public void clearShare(Context context) {
        SharedPreferences sp = context.getSharedPreferences("loginUser", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.commit();
    }

    //  获取储存对象
    public SharedPreferences getInfo(Context context) {
        SharedPreferences sp = context.getSharedPreferences("loginUser", Context.MODE_PRIVATE);
        return sp;
    }

    //    检查网络是否连接
    private boolean isNetworkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return ni != null && ni.isConnectedOrConnecting();
    }


}
